package ifpe.transaction;

import ifpe.datasource.DataSourceFactory;
import java.sql.Connection;
import java.sql.SQLException;

/**
 *
 * @author Sostenes
 */
public class TransactionManagerImpl implements TransactionManager {

    private Connection conn;

    public TransactionManagerImpl() {
        try {
            conn = DataSourceFactory.getInstance().getDataSource().getConnection();
        } catch (SQLException ex) {
            throw new TransactionManagerException(ex);
        }
    }

    @Override
    public void begin(boolean readOnly) {
        try {
            conn.setAutoCommit(false);
            conn.setReadOnly(readOnly);
        } catch (SQLException ex) {
            throw new TransactionManagerException(ex);
        }
    }

    @Override
    public void commit() {
        try {
            if (!conn.isReadOnly()) {
                conn.commit();
            }
        } catch (SQLException ex) {
            throw new TransactionManagerException(ex);
        }
    }

    @Override
    public void rollback() {
        try {
            conn.rollback();
        } catch (SQLException ex) {
            throw new TransactionManagerException(ex);
        }
    }

    @Override
    public void end() {
        try {
            conn.close();
        } catch (SQLException ex) {
            throw new TransactionManagerException(ex);
        }
    }
}
